package Hot100.Medium.HeapAndStack;

import java.util.Stack;

public class LC394_DecodingString {

    public String decodeString(String s) {
        // 存放重复次数的栈
        Stack<Integer> countStack = new Stack<>();
        // 存放字符串的栈
        Stack<StringBuilder> stringStack = new Stack<>();
        // 当前正在构建的字符串
        StringBuilder currentString = new StringBuilder();
        // 当前数字（可能是多位数）
        int currentNumber = 0;

        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                // 构建数字（乘以10是可能处理多位数，如"12"）
                currentNumber = currentNumber * 10 + (c - '0');
            } else if (c == '[') {
                // 遇到'['，把当前数字和字符串分别压栈
                countStack.push(currentNumber);
                stringStack.push(currentString);
                // 重置，开始处理括号内的内容
                currentNumber = 0;
                currentString = new StringBuilder();
            } else if (c == ']') {
                // 遇到']'，计算重复次数并拼接字符串
                int count = countStack.pop();
                StringBuilder temp = currentString;
                currentString = stringStack.pop();

                // 把括号内的字符串重复count次
                for (int i = 0; i < count; i++) {
                    currentString.append(temp);
                }
            } else {
                // 普通字母，直接添加到当前字符串
                currentString.append(c);
            }
        }

        return currentString.toString();
    }

}
